package route

import (
	"bufio"
	"fmt"
	"net/http"
	"os/exec"

	"gitee.com/liumou_site/logger"
	"github.com/gin-gonic/gin"
)

func TracerouteHandler(c *gin.Context) {
	dest := c.DefaultQuery("dest", "8.8.8.8")

	// 使用公共函数验证地址
	validatedDest, err := ValidateAddress(dest)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	logger.Debug("dest:", validatedDest)

	// 设置响应头为流式输出
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")

	// 创建traceroute命令
	cmd := exec.Command("traceroute", validatedDest)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if err := cmd.Start(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 实时读取输出并发送到客户端
	scanner := bufio.NewScanner(stdout)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Fprintf(c.Writer, "data: %s\n\n", line)
		c.Writer.Flush()
	}

	if err := cmd.Wait(); err != nil {
		fmt.Fprintf(c.Writer, "data: Error: %s\n\n", err.Error())
		c.Writer.Flush()
	}
}
